<template>
  <div class="register-section">
    <el-form
      label-position="top"
      label-width="100px"
      :rules="rules"
      :status-icon="true"
      :model="registerForm"
      ref="registerForm"
    >
      <el-form-item label="用户名" prop="name">
        <el-input
          type="text"
          v-model="registerForm.name"
          autocomplete="off"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="registerForm.password"
          autocomplete="off"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submit('registerForm')"
          >注册</el-button
        >
        <el-button @click="reset('registerForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { register } from "@/service";
export default {
  data() {
    return {
      registerForm: {
        name: "",
        password: "",
      },
      /* 表单验证规则 */
      rules: {
        name: { required: true, message: "请输入用户名", trigger: "blur" },
        password: {
          required: true,
          message: "请输入密码",
          trigger: ["blur"],
        },
      },
    };
  },

  methods: {
    submit(formName) {
      // console.log(formName);
      // validate 对整个表单进行校验
      this.$refs[formName].validate((valid, notPass) => {
        if (valid) {
          // 校验通过,向后端提交数据
          register(this.registerForm).then((res) => {
            // console.log(res);
            if (res.code === 1) {
              this.$message({
                message: "该用户名已存在！",
                type: "warning",
              });
              this.reset(formName);
            } else if(res.code === 0) {
              this.$message({
                message: "注册成功,请登录！",
                type: "success",
              });

              this.$router.replace({
                name: "login",
              });
            }
          });
        } else {
          console.log("校验未通过项", notPass);
          return false;
        }
      });
    },
    reset(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
.register-section {
  padding: 10px 20px;
  width: 500px;
  background-color: #fff;
  margin: 0 auto;
  box-shadow: 0 0 25px #cac6c6;
  border-radius: 10px;
}
</style>